//
//  XQPhotoViewModel.swift
//  PhotoSelect
//
//  Created by 王帅强 on 2019/1/7.
//  Copyright © 2019 王帅强. All rights reserved.
//

import Foundation
import Photos

class XQAlbumViewModel {

    lazy var albumList: [XQAlbumModel] = []


    func loadAlbumList(completion: @escaping(_ success: Bool, _ message: String?) -> ()) {

        PHPhotoLibrary.requestAuthorization { (status) in
            if (status == .authorized) {
                self.configList()
                completion(true, nil)
            } else {
                completion(false, "没有相册权限")
            }
        }

    }

    func configList() {
        albumList.removeAll()

        fetchAlbum(type: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil, name: "相机胶卷")

        fetchAlbum(type: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumScreenshots, options: nil, name: "屏幕截图")

        fetchAlbum(type: PHAssetCollectionType.album, subtype: PHAssetCollectionSubtype.albumRegular, options: nil, name: "其他")

    }

    func fetchAlbum(type: PHAssetCollectionType, subtype: PHAssetCollectionSubtype, options: PHFetchOptions?, name: String) {

        let library: PHFetchResult<PHAssetCollection> = PHAssetCollection.fetchAssetCollections(with: type, subtype: subtype, options: nil)

        library.enumerateObjects { (collection, index, stop) in
            let result = PHAsset.fetchAssets(in: collection, options: nil)
            if (result.count > 0) {
                let model = XQAlbumModel(with: collection, name: name)
                self.albumList.append(model)
            }
        }

    }

}
